<?php
/**
 * Created by PhpStorm.
 * User: zcs
 * Date: 17/1/9
 * Time: 上午11:07
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Apply_ajax extends CRUD_Controller {
    public function __construct()
    {
        parent::__construct();
        header("Content-type: application/json");
        date_default_timezone_set('Asia/Shanghai');
        $this->load->model('account_model','maccount');
        $this->load->model('needs_model','mneeds');
        $this->load->model('pay_logs_model', 'mpay_log');
        $this->load->model('balance_detail_model','mbalance');
        $this->load->model('withdrawapply_model','mapply');
    }

    /**
     * 后台执行打款操作(微信)
     */
    public function withdraw_apply_agree(){
        $apply_id = $this->input->post('apply_id');
        if($apply_id){
            $result = $this->mapply->get_one($apply_id);
            if(empty($result)){
                echo json_encode(array('status'=>false,'msg'=>'提现申请不存在，无法进行操作'));exit;
            }else{
                if($this->input->post('is_check')==1){
                    //查看该申请是否已经打款
                    if($result['is_checked']==1){
                        echo json_encode(array('status'=>false,'msg'=>'不可重复打款操作'));exit;
                    }
                    if($result['is_checked']==0){
                        $response = $this->send_money($result['openid'],$result['money']);
                        if($response['result_code']=='SUCCESS' && $response['return_code']=='SUCCESS'){
                            //成功打款则更新该条提现申请记录
                            $update_data = array(
                                'trade_sn'=>$response['payment_no'],
                                'finished'=>$response['payment_time'],
                                'response'=>@json_encode($response),
                                'is_checked'=>1,
                                'updated'=>time()
                            );
                            $this->mapply->update($update_data,array('id'=>$result['id']));
                            $balance = $this->mbalance->get_one(array('pay_code'=>$result['partner_trade_no']));
                            $this->mbalance->set($balance['id'],array('status'=>1,'updated_at'=>time(),'response'=>@json_encode($response),'payment_sn'=>$response['payment_no']));
                            echo json_encode(array('status'=>true,'msg'=>'操作成功！'));exit;
                        }else{
                            //打款失败 可能是余额不足或者其他原因
                            $update_data = array(
                                'updated'=>time(),
                                'response'=>@json_encode($response),
                                'remark'=>$response['err_code_des']
                            );
                            $this->mapply->update($update_data,array('id'=>$result['id']));
                                echo json_encode(array('status'=>false,'msg'=>'微信账户'.$response['err_code_des']));exit;
                            }
                    }
                }else{
                    $cancel_data = array(
                        'updated'=>time(),
                        'is_checked'=>3
                    );
                    $this->mapply->update($cancel_data,array('id'=>$result['id']));
                    echo json_encode(array('status'=>true,'msg'=>'拒绝成功！'));exit;
                }
            }
        }else{
            echo json_encode(array('status'=>false,'msg'=>'参数错误'));exit;
        }
    }


    /**
     * 打款
     */
    public function send_money($openid='',$money='')
    {
        $key='76c055c398bbfd8059357830516cab10';                                //这里的key值要和商户号中的密钥一致且小写
        //请求的url
        $url="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        $rand_num= mt_rand(1000,9999);
        //请求的参数
        $nonce_str=strtoupper(random_string('alnum', '32'));                    //随机字符串
        $mch_billno='1461004902'.date('YmdHis').$rand_num;                      //商户订单号mch_id+yyyymmdd+10位一天内不能重复的数字。
        $mch_id='1461004902';                                                   //商户号
        $wxappid='wx51f72fe2e0317442';                                          //公众账号appid
        $money = $money*100;                                                          //付款金额
        $paras = array(
            'mch_appid'       => $wxappid,
            'mchid'        => $mch_id,
            'nonce_str'     => $nonce_str,
            'partner_trade_no'    => $mch_billno,
            'openid'        =>$openid,
            'check_name'    =>'NO_CHECK',
            'amount'        => $money,
            'desc'          => '余额提现',
            'spbill_create_ip'     => get_ip()
        );
        ksort($paras);
        reset($paras);
        $paras['sign'] = strtoupper(md5(urldecode(http_build_query($paras)) . '&key=' . $key));
        $paras_xml = $this->arrayToXml($paras);
        $this->load->library('curl');
        $this->curl->create($url)->post($paras_xml, array(
            'SSL_VERIFYPEER' => FALSE,
            'SSL_VERIFYHOST' => FALSE,
            'SSLCERT' => LIBS_PATH.'/wxpay/cert/apiclient_cert.pem',
            'SSLKEY' =>LIBS_PATH.'/wxpay/cert/apiclient_key.pem',
            'CAINFO' =>LIBS_PATH.'/wxpay/cert/rootca.pem'
        ));
        $response = (array)simplexml_load_string($this->curl->execute(), 'SimpleXMLElement', LIBXML_NOCDATA);
        return $response;
    }


    /**
     * @param $data
     * @param string $rootNodeName
     * @param null $xml
     * @return mixed
     * @content  数组转化成XML格式
     */
    function arrayToXml($arr){
        $xml = "<root>";
        foreach ($arr as $key=>$val){
            if(is_array($val)){
                $xml.="<".$key.">".$this->arrayToXml($val)."</".$key.">";
            }else{
                $xml.="<".$key.">".$val."</".$key.">";
            }
        }
        $xml.="</root>";
        return $xml;
    }
}
